package com.atguigu.gulimall.gulimallauth.controller;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.gulimallauth.feign.MemberFeignService;
import vo.MemberLoginVo;
import vo.RegisterVo;
import com.atguigu.gulimall.gulimallauth.feign.SmsFeignService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/gulimallauth")
public class LoginController {
    @Autowired
    SmsFeignService smsFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    MemberFeignService memberFeignService;

    @ResponseBody
    @RequestMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        // todo: 接口防刷
        String cacheCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(cacheCode)) {
            long savedTime = Long.parseLong(cacheCode.split("_")[1]);
            if (System.currentTimeMillis() - savedTime < 60000) {
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        String code = UUID.randomUUID().toString().substring(0, 5);
        String codeTimestamp = UUID.randomUUID().toString().substring(0, 5) + "_" + System.currentTimeMillis();

        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, codeTimestamp, 10, TimeUnit.MINUTES);

        return smsFeignService.sendCode(phone, code);
    }


    @PostMapping("/login")
    public String login(MemberLoginVo memberLoginVo, RedirectAttributes redirectAttributes) {
        R r = memberFeignService.login(memberLoginVo);
        if (r.get("code").equals(0)) {
            return "redirect:http://127.0.0.1:20000/index.html";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("errors", (String) r.get("msg"));
            redirectAttributes.addFlashAttribute("errors", "errors");
            return "redirect:http://127.0.0.1:20000/reg.html";
        }
    }


    @PostMapping("/regist")
    public String regist(@Valid RegisterVo registerVo, BindingResult result, RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);

            return "redirect:http://127.0.0.1:20000/reg.html";
        }
        // 真正注册，调用远程服务
        // 1、校验验证码
        String code = registerVo.getCode();
        String cachedCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registerVo.getPhone());
        if (!StringUtils.isEmpty(cachedCode)) {
            if (code.equals(cachedCode.split("_")[0])) {
                // 令牌机制，用完即删
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registerVo.getPhone());

                // 验证码通过，调用远程服务真正注册
                R r = memberFeignService.regist(registerVo);
                if (r.get("code").equals(0)) {
                    return "redirect:http://127.0.0.1:20000/index.html";
                } else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", (String) r.get("msg"));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://127.0.0.1:20000/reg.html";
                }


            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://127.0.0.1:20000/reg.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://127.0.0.1:20000/reg.html";
        }
    }


}
